<?php
namespace app\restaurant\controller;
use app\AdminRest;

use app\ApiRest;
use app\member\model\Member;
use app\member\model\Stored;
use app\restaurant\model\ClassDate;
use app\restaurant\model\Config;
use app\restaurant\model\CouponRecord;
use app\restaurant\model\Delivery;
use app\restaurant\model\Evaluate;
use app\restaurant\model\Printer;
use app\restaurant\model\RefundOrder;
use app\restaurant\model\Store;
use app\restaurant\model\StoreConfig;
use app\restaurant\model\StoreStaff;
use app\restaurant\model\Table;
use app\restaurant\model\TransporterOrder;
use app\restaurant\server\Context;
use app\shop\controller\IndexWxPay;
use app\shop\model\AdminCompany;
use think\App;

use app\restaurant\model\Order as model;

use app\restaurant\model\Car;

use app\restaurant\model\OrderGoods;

use app\restaurant\model\OrderAddress;

use app\restaurant\model\Progress;


use think\facade\Db;


class IndexOrder extends ApiRest
{

    protected $model;

    protected $company;

    protected $car_model;

    protected $order_goods_model;

    protected $address_model;

    protected $progress_model;

    protected $refund_model;

    protected $date_model;

    public function __construct(App $app) {

        parent::__construct($app);

        $this->model   = new Model();

        $this->company = new AdminCompany();

        $this->car_model = new Car();

        $this->order_goods_model = new OrderGoods();

        $this->address_model = new OrderAddress();

        $this->progress_model = new Progress();

        $this->refund_model = new RefundOrder();

        $this->date_model = new ClassDate();


    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:35
     * @功能说明:列表
     */
    public function orderList(){
        //取消过期订单
        $this->model->checkOrder($this->_uniacid,$this->getUserId());

        $this->model->checkEndOrder($this->_uniacid);
        //审核过期售后订单
        $this->refund_model->checkOrder($this->_uniacid,$this->payConfig($this->_uniacid),$this->getUserInfo()['store_id']);

        $input = $this->_param;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.user_id','=',$this->getUserId()];

        $where1 = [];
        //状态
        if(isset($input['pay_type'])&&$input['pay_type']!=999&&empty($input['confirm'])){

            $dis[] = ['a.pay_type','=',$input['pay_type']];
            //已经确认过或者先付款再就餐没有支付的
            $where1[] = ['a.confirm','=',1];

            if($input['pay_type']==0){

                $where1[] = ['a.check_out','=',0];

            }

        }

        if(!empty($input['order_type'])){

            $order_type = $input['order_type']==1?[0,2]:[1];

            $dis[] = ['a.order_type','in',$order_type];

        }
        //待确认
        if(!empty($input['confirm'])){
            //没有确认过
            $dis[] = ['a.confirm','=',0];
            //先就餐再付款 或者支付过
            $where1[] = ['a.check_out','in',[1,2]];

            $where1[] = ['a.transaction_id','<>',0];

        }
        $where = [];
        //商品
        if(!empty($input['goods_name'])){

            $where[] = ['f.goods_name','like','%'.$input['goods_name'].'%'];

            $where[] = ['a.order_code','like','%'.$input['goods_name'].'%'];
        }

        $data = $this->model->orderList($dis,$where,$where1);

        return $this->success($data);

    }



    /**
     * @author chenniang
     * @DataTime: 2020-10-19 10:15
     * @功能说明:支付订单详情
     */
    public function payOrderInfo(){

        $input = $this->_input;

        $coupon_id = !empty($input['coupon_id'])?$input['coupon_id']:0;

        $user_num  = !empty($input['user_num'])?$input['user_num']:0;

        $data = $this->car_model->carListOrder($this->getUserInfo()['store_id'],$input['type'],$this->getUserId(),$this->_uniacid,$coupon_id,$input['address_id'],$user_num);
        //桌号 判断是否是在加餐
        $table_id = $input['type']==1?$this->getUserInfo()['table_id']:0;
        //正在就餐未结算的订单
        $order_id = $this->model->houseNoPayOrder($this->getUserId(),$table_id);

        if(!empty($order_id)){

            $data['check_out'] = 1;

            $data['first_order'] = 0;

        }else{

            $config_model = new Config();

            $config = $config_model->configInfo(['uniacid'=>$this->_uniacid]);

            if($input['type']==1&&$config['check_out']==1){

                $data['check_out'] = 1;

            }else{

                $data['check_out'] = 0;
            }
            //主要用于判断是否现实就餐人数
            $data['first_order'] = $input['type']==1?1:0;

        }
        if($input['type']==1){

            $table_model = new Table();

            $data['table_name'] = $table_model->where(['id'=>$this->getUserInfo()['table_id']])->value('title');
        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-19 11:05
     * @功能说明:支付
     */

    public function payOrder(){

        $input = $this->_input;

        $coupon_id  = !empty($input['coupon_id'])?$input['coupon_id']:0;

        $address_id = !empty($input['address_id'])?$input['address_id']:0;

        $user_num   = !empty($input['user_num'])?$input['user_num']:0;
        //获取购物车里的物品以及几个
        $data = $this->car_model->carListOrder($this->getUserInfo()['store_id'],$input['type'],$this->getUserId(),$this->_uniacid,$coupon_id,$address_id,$user_num);
        //0是外卖 1是堂食 2是自提
        $type = $input['type'];
        //桌号
        $table_id = $type==1?$this->getUserInfo()['table_id']:0;

        $staff_model = new StoreStaff();

        $staff_id = $staff_model->where(['uniacid'=>$this->_uniacid,'store_id'=>$this->getUserInfo()['store_id'],'role'=>1])->value('staff_id');

        if(empty($staff_id)){

            $this->errorMsg('该门店没有管理员，无法下单');
        }

        $staff = Db::name('longbing_card_user_info')->where(['fans_id'=>$staff_id])->find();

        if(empty($staff)||$staff['is_staff']!=1){

            $this->errorMsg('该管理员已被取消员工身份，无法下单');

        }
        //如果是堂食
        if($type==1){
            //正在就餐未结算的订单
            $order_id = $this->model->houseNoPayOrder($this->getUserId(),$table_id);
            //则需要查看桌号绑定的员工
            $table_staff = $this->date_model->tableFindStaff($table_id);

            if(!empty($table_staff['code'])){

                $this->errorMsg($table_staff['msg']);

            }
            //查询该桌号是否有人正在就餐
            $have_order = $this->model->tableHaveOrder($table_id,$this->getUserId());

            if(!empty($have_order)){

                $this->errorMsg('该桌号有其他人正在就餐,请联系店员');

            }

            $staff['fans_id'] = $table_staff['staff_id'];
        }

        $store_model = new Store();
        //门店信息 主要看门店的配送方式
        $store = $store_model->storeInfo(['id'=>$this->getUserInfo()['store_id']]);

        if($type==0&&$store['out']!=1){

            $this->errorMsg('该门店已经关闭外卖，请重新下单');

        }

        if($type==1&&$store['house']!=1){

            $this->errorMsg('该门店已经关闭堂食，请重新下单');

        }

        if($type==2&&$store['self']!=1){

            $this->errorMsg('该门店已经关闭自提，请重新下单');

        }
        //外卖
        if($type==0){

            $delivery_model = new Delivery();

            $res = $delivery_model->checkDistance($this->getUserInfo()['store_id'],$address_id);

            if(!empty($res['code'])){

                $this->errorMsg($res['msg']);

            }
        }

        $order_id = !empty($order_id)?$order_id:0;
        //检测商品信息
        $res = $this->order_goods_model->checkOrderGoods($data['list'],$this->getUserInfo()['store_id'],$this->getUserId(),$order_id);

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);

        }

        $config_model = new Config();

        $config = $config_model->configInfo(['uniacid'=>$this->_uniacid]);

        $insert = [

            'uniacid'       => $this->_uniacid,

            'user_id'       => $this->getUserId(),

            'store_id'      => $this->getUserInfo()['store_id'],

            'pay_type'      => 0,
            //订单号
            'order_code'    => orderCode(),
            //原价
            'init_price'    => $data['init_total_price'],
            //商品总价格
            'goods_price'   => $data['goods_price'],

            'init_goods_price'  => $data['init_goods_price'],
            //餐盒费
            'total_lunch_price' => $data['total_lunch_price'],
            //付款金额
            'pay_price'     => $data['total_price'],

            'member_price'  => $data['member_price'],

            'weight'        => $data['weight'],

            'total_feeding_price' => $data['total_feeding_price'],

            'coupon_price'  => $data['coupon_price'],

            'coupon_id'     => $coupon_id,
            //订单类型 0：外卖 1：堂食 2：自提
            'order_type'    => $type,
            //余额
            'balance'       => $input['is_balance']==1?$data['price']:0,
            //运费
            'express_price' => $data['express_price'],
            //公司
            'company_id'    => $staff['company_id'],

            'staff_id'      => $staff['fans_id'],

            'is_member'     => $data['is_member'],
            //备注
            'order_text'    => $input['order_text'],

            'day'           => date('Y-m-d',time()),

            'check_out'     => $type==1?$config['check_out']:0,

            'table_id'      => $table_id,

            'add_foods_time'=> 0,

            'confirm'       => $type==1?0:1,

            'meal_fee'      => $data['meal_fee'],

            'user_num'      => !empty($input['user_num'])?$input['user_num']:0,

        ];

        Db::startTrans();
        //加菜不需要生成新订单
        if(empty($order_id)){
            //生成订单
            $res = $this->model->orderAdd($insert);

            if($res!=1){

                $this->errorMsg('生成订单失败');

            }
            //订单信息
            $order = $this->model->orderInfo(['order_code'=>$insert['order_code']]);

        }else{
            //加菜
            $res = $this->model->addFoodsOrder($order_id,$insert);

            if(!empty($res['code'])){

                $this->errorMsg($res['msg']);

            }
            //订单信息
            $order = $this->model->orderInfo(['id'=>$order_id]);

        }
        //检测一下三方平台的账号信息以及配送距离检测
        if($order['order_type']==0){

            $context = new Context('',$order['uniacid'],$order['store_id']);

            $res = $context->check($order['store_id']);

            if($res!=1){

                $this->errorMsg($res['msg']);
            }
        }
        //加菜不需要生成新订单所以不需要添加地址
        if(empty($order_id)){
            //添加地址信息
            $res   = $this->address_model->dataAdd($order,$input);

            if($res!=1){

                $this->errorMsg('生成订单失败');

            }

        }
        //增加自订单
        $res   = $this->order_goods_model->orderAdd($order,$data['list']);

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);

        }
        //录入订单进度
        $pro_inser = [

            'uniacid'    => $this->_uniacid,

            'order_code' => $order['order_code'],

            'msg'        => !empty($order_id)?'加菜':'订单已提交',

            'code'       => 0,

            'time'       => time()
        ];

        $res = $this->progress_model->dataAdd($pro_inser);

        if($res!=1){

            $this->errorMsg('生成订单失败');

        }
        //修改优惠券状态
        if(!empty($order['coupon_id'])){

            $record_model = new CouponRecord();

            $record_model->where(['id'=>$order['coupon_id']])->update(['status'=>1]);

        }

        Db::commit();

        $arr['order_info'] = $order;
        //堂食先就餐再结算
        if($order['check_out']==1){

            $arr['pay_list']   = '';

            $p = new Printer();
            //打印小票
            $p->printer($order['id'],1,$order['add_foods_time']);

            return $this->success($arr);
        }
        //余额支付
        if(!empty($order['balance'])){

            $member_model = new Member();

            $member = $member_model->getMemberInfo(['user_id'=>$this->getUserId()]);

            if($order['balance']>$member['stored']){

                $this->errorMsg('余额不足');

            }
            //回调
            $this->model->orderResult($order['order_code'],$order['order_code']);

            $arr['pay_list']   = '';

            return $this->success($arr);

        }
        //如果支付金额是0
        if($order['pay_price']==0){
            //回调
            $this->model->orderResult($order['order_code'],$order['order_code']);

            $arr['pay_list']   = '';

            return $this->success($arr);
        }
        //微信支付
        $pay_controller = new IndexWxPay($this->app);
        //支付
        $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$this->getUserInfo()['openid'],$this->_uniacid,"餐饮",['type' => 'restaurant' , 'out_trade_no' => $order['order_code']],$order['pay_price']);

        $arr['pay_list']= $jsApiParameters;

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-20 09:27
     * @功能说明:订单详情
     */
    public function orderInfo(){

        $store_model = new Store();

        $input = $this->_param;

        $dis = [

            'id' => $input['id']
        ];

        $order = $this->model->orderInfo($dis);

        $config_model = new Config();

        $config = $config_model->configInfo(['uniacid'=>$this->_uniacid]);

        $order['over_time'] = $config['order_over_time']+$order['create_time']-time();

        $order['create_time'] = date('Y-m-d H:i:s',$order['create_time']);

        $order['staff_info']['img']  = lbUserAvatar($order['staff_id']) ;

        $order['staff_info']['name'] = lbUserName($order['staff_id']) ;

        $order['address']  = $this->address_model->dataInfo(['order_id'=>$order['id']]);

        $order['user_img'] = lbUserAvatar($order['user_id']) ;
        //门店信息
        $order['store_info'] = $store_model->where(['id'=>$order['store_id']])->field('title,mobile,long,latitude')->find();

        $transporter_model = new TransporterOrder();
        //配送信息
        $transporter_info  = $transporter_model->orderInfo(['order_id'=>$order['id']],['status','transporter_id','transporter_name','transporter_phone','distance','type','cancel_from']);
        //配送进度
        $transporter_info['progress'] = $this->progress_model->dataList(['order_code'=>$order['order_code']]);

        $order['transporter_info']    = $transporter_info;

        $order['distribution_type']   = !empty($transporter_info['type'])?$transporter_info['type']:0;

        $order['order_refund_time'] = $order['end_time']+$config['order_refund_time']*3600 - time();

        $order['order_refund_time'] = $order['order_refund_time']>0?$order['order_refund_time']:0;
        //是否评价过
        $evaluate_model = new Evaluate();

        $have_evaluate  = $evaluate_model->dataInfo(['order_id'=>$order['id']]);
        //1评价过，0可以评价
        $order['have_evaluate'] = !empty($have_evaluate)||$order['pay_type']!=7?1:0;
        //
        $order_goods['list'] = $this->order_goods_model->orderGoodsListCoupon($order['id']);

        $coupon_record_model = new CouponRecord();
        //堂食
        if($order['order_type']==1){

            $table_model = new Table();

            $order['table_name'] = $table_model->where(['id'=>$order['table_id']])->value('title');
            //可用优惠券
            $order['can_use_coupon'] = $coupon_record_model->canUseCoupon($order_goods,$order['user_id'],$order['uniacid'],$order['order_type'],$order['store_id']);
            //如果传了优惠券说明是堂食下单支付时候
            if(!empty($input['coupon_id'])){

                $data['list'] = $this->order_goods_model->orderGoodsListCoupon($order['id']);

                $data['coupon_id'] = $input['coupon_id'];

                $list = $this->car_model->getTruePayPrice($data);

                $order['coupon_price'] = $order['pay_price'] > $list['discount_price']?$list['discount_price']:$order['pay_price'];

                $order['pay_price']    = round($order['pay_price'] - $order['coupon_price'],2);

                foreach ($order['order_goods'] as &$v){

                    foreach ($list['list'] as $vs){

                        if($v['id'] == $vs['id']){

                            $v['pay_price']     = round($vs['true_price']*$v['goods_num'],2);

                            $v['feeding_price'] = round($vs['feeding_price']*$v['goods_num'],2);


                        }

                    }

                }

            }

            $order['order_goods'] = $this->order_goods_model->houseOrderGoods($order['id']);
        }

        return $this->success($order);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-04 15:08
     * @功能说明:先就餐后付款 支付
     */
    public function underPayOrder(){

        $input = $this->_input;

        $order = $this->model->orderInfo(['id'=>$input['id']]);

        if(empty($order)||$order['pay_type']!=0){

            $this->errorMsg('订单状态错误');
        }

        if(!empty($input['coupon_id'])){

            if(!empty($order['coupon_id'])){

                $this->errorMsg('该订单已使用优惠券');
            }

            $data['list'] = $this->order_goods_model->orderGoodsListCoupon($order['id']);

            $data['coupon_id'] = $input['coupon_id'];

            $list = $this->car_model->getTruePayPrice($data);

            Db::startTrans();

            foreach ($list['list'] as $value){

                $update = [

                    'pay_price'     => round($value['true_price']*$value['goods_num']),

                    'feeding_price' => round($value['feeding_price']*$value['goods_num'])
                ];

                $res = $this->order_goods_model->orderUpdate(['id'=>$value['id']],$update);

                if($res!=1){

                    Db::rollback();

                    $this->errorMsg('优惠券抵扣失败');

                }

            }

            $record_model = new CouponRecord();

            $res = $record_model->where(['id'=>$input['coupon_id']])->update(['status'=>1]);


            if($res!=1){

                Db::rollback();

                $this->errorMsg('优惠券抵扣失败');

            }
            //修改订单
            $order_update = [

                'coupon_price'  => $order['goods_price']>$list['discount_price']?$list['discount_price']:$order['goods_price'],

                'pay_price'     => round($order['pay_price'] - $list['discount_price'],2)>=0?round($order['pay_price'] - $list['discount_price'],2):0,

                'coupon_id'     => $input['coupon_id'],
            ];

            $res = $this->model->orderUpdate(['id'=>$input['id']],$order_update);

            if($res!=1){

                Db::rollback();

                $this->errorMsg('优惠券抵扣失败');

            }

            Db::commit();

        }

        $res = $this->model->orderUpdate(['id'=>$input['id']],['check_out'=>2]);

        if($res!=1){

            Db::rollback();

            $this->errorMsg('支付失败');

        }

        $order = $this->model->orderInfo(['id'=>$input['id']]);
        //如果支付金额是0
        if($order['pay_price']==0){
            //回调
            $this->model->orderResult($order['order_code'],$order['order_code']);

            $arr['pay_list']   = '';

            return $this->success($arr);
        }
        //微信支付
        $pay_controller = new IndexWxPay($this->app);
        //支付
        $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$this->getUserInfo()['openid'],$this->_uniacid,"餐饮",['type' => 'restaurant' , 'out_trade_no' => $order['order_code']],$order['pay_price']);

        $arr['pay_list']= $jsApiParameters;

        return $this->success($arr);


    }



    /**
     * @author chenniang
     * @DataTime: 2020-10-20 13:58
     * @功能说明:加菜接口
     */
    public function addOrderGoods(){

        $input = $this->_input;

        $order = $this->model->order(['id'=>$input['id']]);

        if(empty($order)||$order['pay_type']!=0){

            $this->errorMsg('订单状态错误');
        }

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.store_id','=',$this->getUserInfo()['id']];

        $dis[] = ['a.user_id','=',$this->getUserId()];
        //获取购物车里的物品以及几个
        $data  = $this->car_model->carList($dis,$input['type'],$this->getUserId(),$this->_uniacid);
        //检测商品信息
        $res = $this->order_goods_model->checkOrderGoods($data['list'],$this->getUserInfo()['store_id'],$this->getUserId(),$order['id']);

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);

        }
        //重新编辑价格
        $order['init_price'] += $data['init_total_price'];

        $order['goods_price']+= $data['goods_price'];

        $order['lunch_fee']  += $data['lunch_fee'];

        $order['pay_price']  += $data['total_price'];

        Db::startTrans();
        //修改订单
        $res = $this->model->orderUpdate(['id'=>$order['id']],$order);

        if($res!=1){

            $this->errorMsg('加菜失败');

        }
        //增加自订单
        $res = $this->order_goods_model->orderAdd($order,$data['list']);

        if($res!=1){

            $this->errorMsg('加菜失败');

        }

        Db::commit();

        return $this->success($order);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-20 14:31
     * @功能说明:重新支付订单
     */
    public function rePayOrder(){

        $input = $this->_input;

        $order = $this->model->orderInfo(['id'=>$input['id']]);

        if(empty($order)||$order['pay_type']!=0){

            $this->errorMsg('订单状态错误');
        }
        //检测一下三方平台的账号信息
        if($order['order_type']==0){

            $context = new Context($order['uniacid'],$order['store_id']);

            $res = $context->check();

            if($res!=1){

                $this->errorMsg($res['msg']);
            }

        }
        //堂食订单
        if(!empty($input['coupon_id'])&&$order['check_out']==1&&$order['order_type']==1){

            if(!empty($order['coupon_id'])){

                $this->errorMsg('该订单已使用优惠券');
            }

            $data['list'] = $this->order_goods_model->orderGoodsListCoupon($order['id']);

            $data['coupon_id'] = $input['coupon_id'];

            $list = $this->car_model->getTruePayPrice($data);

            Db::startTrans();

            foreach ($list['list'] as $value){

                $update = [

                    'pay_price'     => round($value['true_price']*$value['num'],2),

                    'feeding_price' => round($value['feeding_price']*$value['num'],2)
                ];

                $res = $this->order_goods_model->orderUpdate(['id'=>$value['id']],$update);


            }

            $record_model = new CouponRecord();

            $res = $record_model->where(['id'=>$input['coupon_id']])->update(['status'=>1]);

            if($res!=1){

                Db::rollback();

                $this->errorMsg('优惠券抵扣失败');

            }
            //修改订单
            $order_update = [

                'coupon_price'  => $order['goods_price']>$list['discount_price']?$list['discount_price']:$order['goods_price'],

                'pay_price'     => round($order['pay_price'] - $list['discount_price'],2)>=0?round($order['pay_price'] - $list['discount_price'],2):0,

                'coupon_id'     => $input['coupon_id'],
            ];

            $res = $this->model->orderUpdate(['id'=>$input['id']],$order_update);

            if($res!=1){

                Db::rollback();

                $this->errorMsg('优惠券抵扣失败');

            }

            Db::commit();

        }

        if($order['order_type']==1&&$order['check_out']==1){

            $res = $this->model->orderUpdate(['id'=>$input['id']],['check_out'=>2]);

        }

        $order = $this->model->orderInfo(['id'=>$input['id']]);
        //如果支付金额是0
        if($order['pay_price']==0){
            //回调
            $this->model->orderResult($order['order_code'],$order['order_code']);

            $arr['pay_list']   = '';

            return $this->success($arr);
        }
        //余额支付
        if(!empty($order['balance'])){

            $member_model = new Member();

            $member = $member_model->getMemberInfo(['user_id'=>$this->getUserId()]);

            if($order['balance']>$member['stored']){

                $this->errorMsg('余额不足');

            }
            //回调
            $this->model->orderResult($order['order_code'],$order['order_code']);

            $arr['pay_list']   = '';

            return $this->success($arr);

        }
        //微信支付
        $pay_controller = new IndexWxPay($this->app);
        //支付
        $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$this->getUserInfo()['openid'],$this->_uniacid,"餐饮",['type' => 'restaurant' , 'out_trade_no' => $order['order_code']],$order['pay_price']);

        $arr['order_info'] = $order;

        $arr['pay_list']   = $jsApiParameters;

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-23 09:53
     * @功能说明:取消订单
     */
    public function cancelOrder(){

        $input = $this->_input;

        $order = $this->model->orderInfo(['id'=>$input['id']]);

        if($order['order_type']==1&&$order['check_out']!=0){

            $this->errorMsg('堂食订单无法取消，请联系店员');
        }

        $res   = $this->model->cancelOrder($input['id'],$this->payConfig());

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);
        }

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-27 15:36
     * @功能说明:订单自提码
     */
    public function orderQr(){

        $input = $this->_input;

        $order = $this->model->orderInfo(['id'=>$input['id']]);

        $qr = '';

        if(empty($order['qr'])&&$order['order_type']==2){

            $qr = $this->model->orderQr($input,$this->_uniacid);

        }

        return $this->success($qr);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-04 09:22
     * @功能说明:用户可以退款的订单
     */
    public function userCanRefundOrder(){

        $input = $this->_input;

        $order = $this->model->orderInfo(['id'=>$input['id']]);

        if($order['pay_type']<1){

            $this->errorMsg('订单未支付或已经取消');
        }

        $dis[] = ['order_id','=',$input['id']];

        $dis[] = ['can_refund_num','>',0];

        $data  = $this->order_goods_model->where($dis)->select()->toArray();

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-04 10:20
     * @功能说明:申请售后
     */
    public function applyRefundOrder(){

        $input = $this->_input;

        $order = $this->model->orderInfo(['id'=>$input['order_id']]);

        $config_model = new Config();

        $config = $config_model->configInfo(['uniacid'=>$this->_uniacid]);

        $order_refund_time = $order['end_time']+$config['order_refund_time']*3600 - time();

        if($order_refund_time<0&&$order['pay_type']==7){

            $this->errorMsg('已超过可申请退款时间');
        }

        $refund_model = new RefundOrder();
        //申请退款
        $res   = $refund_model->applyRefundOrder($order,$input['list'],$input['cancel_reason'],$input['cancel_img']);

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);
        }

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-05 09:29
     * @功能说明:商家端退款订单
     */
    public function refundOrderList(){
        //审核过期售后订单
        $this->refund_model->checkOrder($this->_uniacid,$this->payConfig($this->_uniacid),$this->getUserInfo()['store_id']);

        $input = $this->_input;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.user_cancel','=',0];

        $dis[] = ['a.user_id','=',$this->getUserId()];

        if(!empty($input['status'])){

            $dis[] = ['a.status','=',$input['status']];
        }

        if(isset($input['order_type'])&&$input['order_type']!=999){

            $dis[] = ['b.order_type','=',$input['order_type']];
        }

        $where = [];

        if(!empty($input['name'])){

            $where[] = ['c.goods_name','like','%'.$input['name'].'%'];

            $where[] = ['b.order_code','like','%'.$input['name'].'%'];

            $where[] = ['a.order_code','like','%'.$input['name'].'%'];
        }

        $data = $this->refund_model->refundOrderList($dis,$where);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-05 13:42
     * @功能说明:退款订单详情
     */
    public function refundOrderInfo(){

        $input = $this->_input;

        $store_model       = new Store();

        $progress_model    = new Progress();

        $transporter_model = new TransporterOrder();

        $order = $this->refund_model->orderInfo(['id'=>$input['id']]);
        //用户信息
        $order['address']    = $this->address_model->dataInfo(['order_id'=>$order['order_id']]);
        //用户头像
        $order['user_img']   = lbUserAvatar($order['user_id']) ;
        //门店信息
        $order['store_info'] = $store_model->where(['id'=>$order['store_id']])->field('title,mobile')->find();
        //支付订单
        $pay_order = $this->model->orderInfo(['id'=>$order['order_id']]);
        //当前进度
        $order['now_progress'] = $progress_model->nowOrderTextRefund($pay_order['order_code']);
        //当前骑手状态
        $order['transporter_status'] = $transporter_model->where(['order_id'=>$order['order_id']])->value('status');
        //查看是什么配送
        $order['distribution_type']  = $transporter_model->where(['order_id'=>$order['order_id']])->value('type');

        $order['sh_time']     = !empty($order['sh_time'])?date('Y-m-d H:i:s',$order['sh_time']):0;
        //支付订单号
        $order['pay_order_code']  = $pay_order['order_code'];
        //订单类型
        $order['pay_order_type']  = $pay_order['order_type'];
        //订单下单时间
        $order['pay_create_time'] = date('Y-m-d H:i:s',$pay_order['create_time']);
        //退款完成时间
        $config_model = new Config();

        $config = $config_model->configInfo(['uniacid'=>$this->_uniacid]);

        $order['refund_success_time'] = $order['create_time']+$config['refund_success_time']*60 - time();

        $order['refund_success_time'] = $order['refund_success_time']>0?$order['refund_success_time']:0;

        $order['create_time'] = date('Y-m-d H:i:s',$order['create_time']);


        return $this->success($order);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-05 16:27
     * @功能说明:用户取消退款
     */

    public function userCancelRefund()
    {

        $input = $this->_input;

        $order = $this->refund_model->orderInfo(['id'=>$input['id']]);

        if($order['status']==2){

            $this->errorMsg('订单已退款');
        }

        if($order['status']==3){

            $this->errorMsg('订单已拒绝退款');
        }

        if($order['user_cancel']==1){

            $this->errorMsg('退款申请已取消');

        }

        Db::startTrans();

        $res = $this->refund_model->orderUpdate(['id'=>$input['id']],['user_cancel'=>1]);

        if($res!=1){

            $this->errorMsg('取消失败');

        }

        foreach ($order['order_goods'] as $v){

            $num = $v['goods_num'];

            $res = $this->order_goods_model->where(['id'=>$v['order_goods_id']])->update(['can_refund_num'=>Db::raw("can_refund_num+$num")]);

            if($res!=1){

                $this->errorMsg('取消失败');

            }
        }

        Db::commit();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-06 16:22
     * @功能说明:获取骑手距离
     */
    public function transporterLocation(){

        $input = $this->_param;
        //订单
        $order = $this->model->orderInfo(['id'=>$input['order_id']]);

        $order_adress = $this->address_model->dataInfo(['order_id'=>$order['id']]);

        $context = new Context($order['order_code']);

        $send_order = $context->orderInfo($order['order_code']);

        if(empty($send_order['code'])){

            $arr['transporterName']  = $send_order['transporterName'];

            $arr['transporterPhone'] = $send_order['transporterPhone'];

            $arr['transporterLng']   = $send_order['transporterLng'];

            $arr['transporterLat']   = $send_order['transporterLat'];

            $arr['distance'] = getdistance($order_adress['long'],$order_adress['lat'],$arr['transporterLng'],$arr['transporterLat']);

            $store_model = new Store();

            $arr['distance'] = $store_model->getDistanceAttr($arr['distance']);

            return $this->success($arr);
        }

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-06 17:09
     * @功能说明:用户确认收货
     */
    public function userEndOrder(){

        $input = $this->_input;

        $order = $this->model->orderInfo(['id'=>$input['order_id']]);

        if($order['pay_type']!=1){

            $this->errorMsg('订单状态错误');
        }

        $res = $this->model->endOrder($order['id']);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-03 10:23
     * @功能说明:添加评价
     */
    public function evaluateAdd(){

        $input = $this->_input;

        $order = $this->model->orderInfo(['id'=>$input['id']]);

        $insert = [

            'uniacid' => $this->_uniacid,

            'order_id'=> $order['id'],

            'store_id'=> $order['store_id'],

            'user_id' => $this->getUserId(),

            'text'    => $input['text'],

            'imgs'    => !empty($input['imgs'])?implode(',',$input['imgs']):'',

            'star'    => $input['star']
        ];

        $evaluate_model = new Evaluate();

        $have = $evaluate_model->dataInfo(['order_id'=>$input['id']]);

        if(!empty($have)){

            $this->errorMsg('你已经评价过了');
        }

        $res = $evaluate_model->dataAdd($insert);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-03 15:06
     * @功能说明:门店评价列表
     */
    public function evaluateList(){

        $input = $this->_param;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.store_id','=',$this->getUserInfo()['store_id']];

        $dis[] = ['a.status','=',1];

        if(!empty($input['type'])){

            if($input['type']==1){

                $dis[] = ['a.star','>',2];

            }else{

                $dis[] = ['a.star','<',3];
            }

        }

        $evaluate_model = new Evaluate();

        $data = $evaluate_model->adminList($dis,10);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-03 09:34
     * @功能说明:获取好评差评数量
     */
    public function evaluateCount(){

        $dis[] = ['uniacid','=',$this->_uniacid];

        $dis[] = ['store_id','=',$this->getUserInfo()['store_id']];

        $dis[] = ['status','>',-1];

        $evaluate_model = new Evaluate();
        //好评数量
        $data['goods_evaluate'] = $evaluate_model->where($dis)->where('star','>',2)->count();
        //差评数量
        $data['bad_evaluate']   = $evaluate_model->where($dis)->where('star','<=',2)->count();

        $data['all_evaluate']   = $evaluate_model->where($dis)->count();

        return $this->success($data);

    }


}
